有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java从http url获取文件扩展名

现在我从apache知道了FilenameUtils.getExtension()

但在我的例子中,我正在处理来自http(s)URL的扩展,所以在我的例子中

https://your_url/logo.svg?position=5

此方法将返回svg?position=5

有没有处理这种情况的最佳方法?我的意思是不用我自己写这个逻辑


共 (2) 个答案

  1. # 1 楼答案

    如果您想要一个Brand NosiNess®解决方案,那么在剥离查询字符串后考虑使用Apache方法,如果存在的话席:

    String url = "https://your_url/logo.svg?position=5";
    url = url.replaceAll("\\?.*$", "");
    String ext = FilenameUtils.getExtension(url);
    System.out.println(ext);
    

    如果您想要一个甚至不需要外部库的一个内衬,那么使用^ {CD1>}:

    考虑这个选项。
    String url = "https://your_url/logo.svg?position=5";
    String ext = url.replaceAll(".*/[^.]+\\.([^?]+)\\??.*", "$1");
    System.out.println(ext);
    
    svg
    

    下面是对上面使用的正则表达式模式的解释:

    .*/     match everything up to, and including, the LAST path separator
    [^.]+   then match any number of non dots, i.e. match the filename
    \.      match a dot
    ([^?]+) match AND capture any non ? character, which is the extension
    \??.*    match an optional ? followed by the rest of the query string, if present
    
  2. # 2 楼答案

    您可以使用JAVA中的URL库。在这种情况下,它有很多用处。你应该这样做:

    String url = "https://your_url/logo.svg?position=5";
    URL fileIneed = new URL(url);
    

    然后,对于“fileined”变量有很多getter方法。在您的情况下,“getPath()”将检索以下内容:

    fileIneed.getPath()  -> "/logo.svg"
    

    然后使用您正在使用的Apache库,您将获得“svg”字符串

    FilenameUtils.getExtension(fileIneed.getPath())  -> "svg"
    

    JAVA URL library docs >>> https://docs.oracle.com/javase/7/docs/api/java/net/URL.html